package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.utils.LiveAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

    @Autowired
    private LiveRoomMapper liveRoomMapper;

    @Autowired
    private LiveAddressUtil liveAddressUtil;

    @Override
    public LiveRoom getCurrentLive() {
        Long userId = AuthContextHolder.getUserId();
        return liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
                .eq(LiveRoom::getUserId, userId).ge(LiveRoom::getExpireTime, new Date()));
    }

    @Override
    public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo) {
        //获取userId
        Long userId = AuthContextHolder.getUserId();
        //查询是否有未过期的直播间
        LiveRoom DbLiveRoom = liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>()
                .eq(LiveRoom::getUserId, userId).ge(LiveRoom::getExpireTime, new Date()));
        if (DbLiveRoom != null) {
            return DbLiveRoom;
        }
        //保存新建直播间
        LiveRoom liveRoom = new LiveRoom();
        BeanUtils.copyProperties(liveRoomVo, liveRoom);
        //设置userId
        liveRoom.setUserId(userId);
        //设置直播状态
        liveRoom.setStatus("1");
        //设置appName
        liveRoom.setAppName("国服韩信直播间");
        //设置streamName
        liveRoom.setStreamName("wz" + IdWorker.getIdStr());

        long exTime = liveRoom.getExpireTime().getTime();
        TencentLiveAddressVo tencentLiveAddresses = liveAddressUtil.getTencentLiveAddresses(exTime / 1000, liveRoom.getStreamName());
        //设置推流地址
        liveRoom.setPushUrl(tencentLiveAddresses.getPushWebRtcUrl());
        //设置播放地址
        liveRoom.setPlayUrl(tencentLiveAddresses.getPullWebRtcUrl());
        //保存新建直播间
        this.save(liveRoom);
        return liveRoom;
    }
}
